package com.example.shiwu;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.shiwu.adapter.AlarmAdapter;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.vo.AlarmVo;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.AlarmService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.SocketMergeCallBackAlarmUtils;
import com.example.shiwu.util.SocketMergeUtils;
import com.example.shiwu.view.MainInfoView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class AlarmListActivity extends AppCompatActivity implements AlarmAdapter.MyClickListener {

    private CheckBox checkBox,send_items_checkbox;
    private RefreshLayout mRefreshLayout;
    private boolean checkSta = false;
    public TextView title_text, title_seting,did;
    private Button allCheak;
    public ImageView title_back;
    private Context myContext;
    private ListView listView;
    private AlarmAdapter myAdapter;
    private List<Map<String, Object>> listitem;
    private ItemsService itemsService;
   // private SendsService alarmService;
    private AlarmService alarmService;
    private ArrayList<AlarmVo> alarmLisAll = null;
    private Button expor_btn,alarm_del_btn;
    private int currentPage = 1;
    private int pageSize = 3;
    private int totalSize = 0;
    private String ids = "";
    private List<Integer> idlis = new ArrayList<Integer>();

//    private SocketConnectThread mConnectThread;
//    private SocketReceiveThread mReceiveThread;
    private SocketMergeCallBackAlarmUtils socketUtils;
    private MainInfoView mainInfoView;
    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;
    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_DEVICE_INIT = 6;
    private static final int MSG_ALARM_CLEAR = 7;
    private static final int MSG_SEND_DATA = 6;
    public Socket mSocket;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private final int DEFAULT_PORT = 8086;
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;
    private int success_count = 0;
    private Boolean bool = true;
    private ArrayList<String> msgArray;
    private MyQueue queue;
    private DataParseUtil dataParseUtil;
    private DeviceService deviceService;
    private String itemsId;
    private DatabaseHelper dbHelper;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_SOCKET_CONNECT:
                    mSocketConnectState = STATE_CONNECTED;
                    System.out.println(R.string.disconnect);
//                    mReceiveThread = new SocketReceiveThread();
//                    mReceiveThread.start();
                    break;
                case MSG_SOCKET_DISCONNECT:
                    System.out.println(R.string.connect);
                    mSocketConnectState = STATE_DISCONNECTED;
                   // closeConnection();
                    break;
                case MSG_SOCKET_CONNECTFAIL:
                    mSocketConnectState = STATE_DISCONNECTED;
                    System.out.println("======================连接失败=========================");
//                    mReceiveThread = new SocketReceiveThread();
//                    mReceiveThread.start();
                    break;
                case MSG_RECEIVE_DATA:

                    ArrayList msglis = (ArrayList) msg.obj;
                    if(msglis.size()>0){
//                        Alarm alarm1 = new Alarm();
//                        alarm1.setAlarmMsg((String) msglis.get(0));
//                        alarm1.setSn((String) msglis.get(1));
//                        alarm1.setItemId(itemsId);
//                        alarm1.setStatus(0);
//                        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                        Date date = new Date(System.currentTimeMillis());
//                        alarm1.setCreateTime(sim.format(date));
//                        alarm1.setUpdateTime(sim.format(date));
//                        alarmService.save(alarm1);
                        socketUtils.msgAlarmArray.clear();
                        socketUtils.clear_alram = 0;
                    }

                    break;
                case MSG_DEVICE_INIT:
                    getDeviceLisAll();
                    bingAll();
                    break;
                case MSG_ALARM_CLEAR:
                    Integer msglis2 = (Integer) msg.obj;
                    if(msglis2 != null){
                        String clear = "告警已解除！";
                        Toast.makeText(myContext, clear, Toast.LENGTH_SHORT).show();
                        socketUtils.msgAlarmArray.clear();
                        Alarm alarm1 = new Alarm();
                        alarm1.setId(msglis2);
                        //alarm1.setItemId(itemsId);
                        alarm1.setStatus(1);
                        alarmService.updade(alarm1,new Alarm(msglis2));
                        updataData();
                    }

                default:
                    break;
            }
        }
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_list);
        myContext = this;
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        //send_items_checkbox = findViewById(R.id.send_items_checkbox);
        alarmLisAll = new ArrayList<AlarmVo>();
        alarmService = new AlarmService();
        allCheak = findViewById(R.id.allCheakAlarm);
        alarm_del_btn = findViewById(R.id.alarm_del_btn);
        dbHelper = new DatabaseHelper(this);
        title_text.setText("告警记录");
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlarmListActivity.this.finish();
            }
        });

        //getDeviceLisAll();
        Items items = findSelectItem();

        itemsId = items.getId().toString();

        //dataParseUtil = new DataParseUtil();
        //closeConnection();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (socketUtils == null) {
                    socketUtils = SocketMergeCallBackAlarmUtils.getInstance(myContext);
                    try {
                        Thread.sleep(100);
                        if(socketUtils.socket == null){
                            Message msg = new Message();
                            msg.what = MSG_DEVICE_INIT;
                            mHandler.sendMessage(msg);

                            return;
                        }else {
                            SocketMergeUtils.success_count_alram = 0;
                            socketListener();
                            bingAll();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }


                    //socketUtils.stopMainInfoListening();
                }//启动socket
            }
        }).start();

        //startConnect();
        queue = new MyQueue();

        alarm_del_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("——————————————删除——————————————————");
                if(ids.length() == 0){
                    return;
                }
                String ids1 = ids.substring(0,ids.length()-1);
                List<String> idLis = new ArrayList<>();
                if(ids1.length()>1){
                    String[] idLis1 = ids1.split(",");
                    idLis.addAll(Arrays.asList(idLis1));
                }else{
                    idLis.add(ids1);
                }

                if(idLis.size()>0){
                    for (int i = 0; i < idLis.size(); i++) {
                        Alarm ala = new Alarm();
                        ala.setId(Integer.parseInt(idLis.get(i)));
                        List<Alarm> svlis = alarmService.getAlarm(ala);
                        if(svlis.size()>0){
                            if(idLis.get(i).equals(String.valueOf(svlis.get(0).getId()))){
                                int itemId = Integer.parseInt(svlis.get(0).getItemId());
                                int sId = svlis.get(0).getId();
                                Alarm sen1 = new Alarm();
                                sen1.setStatus(2);
                                sen1.setId(sId);
                                Alarm sen2 = new Alarm();
                                sen2.setId(sId);
                                Boolean bool = alarmService.updade(sen1,sen2);
                                if(bool){
                                    updataData();
                                    Toast.makeText(myContext, "删除成功！", Toast.LENGTH_SHORT).show();
                                }

                            }

                        }
                    }
                }
            }
        });

        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getItemsDataHeaderPull();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { //上拉加载更多
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getItemsDataFooterPull();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });


        listView = (ListView) findViewById(R.id.alarm_list_view);
        bingAll();


    }
    private void bingAll(){
        //Items items1 = null;
        try {
            //items1 = findSelectItem();
            if("" != itemsId){
                Device dev = new Device();
                dev.setItemId(itemsId);
                int count =alarmLisAll.size();
                if(count>0){
                    allCheak.setOnClickListener(new  View.OnClickListener(){
                        @Override
                        public void onClick(View view) {
                            if(checkSta){
                                btnNoList();
                                allCheak.setText("全选");
                            }else{
                                btnSelectAllList();
                                allCheak.setText("全不选");
                            }

                        }
                    });
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(socketUtils!=null){
            socketUtils.releaseSocket();
        }

    }
    public void initText(){

    }
    public void initData(){

    }
    public Items findSelectItem(){
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return items1;
    }
    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }
    public void updataData(){
        alarmLisAll = new ArrayList<AlarmVo>();
        currentPage = 1;
        getDeviceLisAll();
        myAdapter.cleckAll();
    }
    public void clearAlarm(Integer sId){
        Message msg = new Message();
        msg.what = MSG_ALARM_CLEAR;
        msg.obj = sId;
        mHandler.sendMessage(msg);
    }

    public void getDeviceLisAll() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);

        Items item = findSelectItem();
       // List<AlarmVo> send = alarmService.getAll((currentPage * pageSize), pageSize,item.getId());
        List<AlarmVo> deviceLis = performJoinQuery(item.getId().toString());
        currentPage+=1;
        alarmLisAll.addAll(deviceLis);
        //创建一个simpleAdapter
        myAdapter = new AlarmAdapter(AlarmListActivity.this, alarmLisAll, R.layout.alarm_list_item,modeData,this);
        listView = findViewById(R.id.alarm_list_view);
        listView.setAdapter(myAdapter);
    }
    private void getItemsDataHeaderPull() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        currentPage =1;
        alarmLisAll= null;
        alarmLisAll = new ArrayList<AlarmVo>();
        //List<AlarmVo> send = alarmService.getAll((currentPage * pageSize), pageSize,item.getId());
        List<AlarmVo> deviceLis = performJoinQuery(item.getId().toString());
        currentPage+=1;
        alarmLisAll.addAll(deviceLis);
        //创建一个simpleAdapter
        myAdapter = new AlarmAdapter(AlarmListActivity.this, alarmLisAll, R.layout.alarm_list_item,modeData,this);
        listView = findViewById(R.id.alarm_list_view);
        listView.setAdapter(myAdapter);

    }

    private void getItemsDataFooterPull() {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        //List<AlarmVo> deviceLis = alarmService.getAll((currentPage * pageSize), pageSize,item.getId());
        List<AlarmVo> deviceLis = performJoinQuery(item.getId().toString());
        if(deviceLis.size()>0){
            alarmLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new AlarmAdapter(AlarmListActivity.this, alarmLisAll, R.layout.alarm_list_item,modeData,this);
            currentPage ++;
            myAdapter.notifyDataSetChanged();
        }
    }
    private List<AlarmVo> performJoinQuery(String itemId) {
        int limit = (currentPage-1)*pageSize;
        String type = "0";
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // SQL语句：查询用户表和订单表，根据用户ID关联
        Cursor cursor = db.query("tb_alarm alarm left join tb_items ite on ite.id = alarm.item_id left join tb_device dev on dev.item_id = alarm.item_id ",
                new String[]{"alarm.id","ite.name","ite.id as itemId","alarm.status as status","alarm.alarm_msg as alarmMsg","dev.sn","alarm.create_time as createTime,alarm.send_id"},
                " alarm.status != 2 and ite.id =? ",
                new String[]{itemId},"alarm.id","","alarm.id DESC", String.valueOf(limit)+","+String.valueOf(pageSize));
        System.out.println(cursor.getCount());
        List<AlarmVo> lis = new ArrayList<>();
        // 遍历结果集
        while (cursor.moveToNext()) {
            AlarmVo AlarmVo = new AlarmVo();
            String id = cursor.getString(0);
            AlarmVo.setId(id);
            String name = cursor.getString(1);
            AlarmVo.setName(name);
            int itemId1 = cursor.getInt(2);
            AlarmVo.setItemId(itemId1);
            Integer status = cursor.getInt(3);
            AlarmVo.setStatus(status);
            String alarmMsg = cursor.getString(4);
            AlarmVo.setAlarmMsg(alarmMsg);
            String sn = cursor.getString(5);
            AlarmVo.setSn(sn);
            String createTime = cursor.getString(6);
            AlarmVo.setCreateTime(createTime);
            String sendId = cursor.getString(7);
            AlarmVo.setSendId(sendId);
            lis.add(AlarmVo);

            // 处理查询结果
            // ...
        }

        cursor.close();
        db.close();
        return lis;
    }
    /**
     * 全选
     * @param
     */
    public void btnSelectAllList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);

            checkBox = lin.findViewById(R.id.alarm_items_checkbox);

            if(checkBox != null){
                checkBox.setChecked(true);
            }else {
                checkBox.setChecked(false);
            }
            checkSta = true;
//            did = lin.findViewById(R.id.did);
//            String id = (String) did.getText();
//            ids += id+",";

        }
    }

    /**
     * 全不选
     * @param
     */
    public void btnNoList() {

        int count = listView.getCount();
        for (int i = 0; i < count; i++) {
            View lin = listView.getChildAt(i);
//            checkBox = lin.findViewById(R.id.send_list_items_checkbox);
//            if(checkBox != null){
//                checkBox.setChecked(false);
//            }else {
//                checkBox.setChecked(true);
//            }
//
            checkSta = false;
//            did = lin.findViewById(R.id.did);
//            String id = (String) did.getText();
//            ids += id+",";
//            System.out.println("----ids----"+ids);
        }
        ids = "";
        updataData();
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void clickListener(View v) {
        System.out.println("---------------------------v= "+v.getId());
        int id = v.getId();
        if(id>0){
            idlis.add(id);
        }else {
            String id1 = String.valueOf(id).substring(1);
            for (int i = 0; i < idlis.size(); i++) {
                if(idlis.get(i) == Integer.parseInt(id1)){
                    idlis.remove(i);
                }
            }

        }
        System.out.println("---------------------------idlis= "+idlis);
//        if(idlis.size()==listView.getCount()){
//            send_items_checkbox.setChecked(true);
//            checkSta = true;
//        } else if (idlis.size()== 0) {
//            send_items_checkbox.setChecked(false);
//            checkSta = false;
//        }
        ids = "";
        for (int i = 0; i < idlis.size(); i++) {
            ids += idlis.get(i)+",";
        }
    }

    @Override
    public boolean clickRemoveListener(int position) {
        removeItemsDataUpdata(position);
        updateItem(position);
        return true;
    }
    private void removeItemsDataUpdata(int position) {
        Resources res =getResources();
        String[] modeData=res.getStringArray(R.array.modeData);
        Items item = findSelectItem();
        //List<AlarmVo> deviceLis = alarmService.getAll((currentPage * 1), 1,item.getId());
        List<AlarmVo> deviceLis = alarmService.getAll((currentPage * 1), 1,item.getId());
        if(deviceLis.size()>0){
            alarmLisAll.remove(position);
            alarmLisAll.addAll(deviceLis);
            //创建一个simpleAdapter
            myAdapter = new AlarmAdapter(AlarmListActivity.this, alarmLisAll, R.layout.alarm_list_item,modeData,this);
            //myAdapter.notifyDataSetChanged();
        }
    }
    private void updateItem(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            myAdapter.getView(position, view, listView);
        }

    }
    private void socketListener() {
        if(socketUtils.mMainInfoThread != null){
            socketUtils.stopMainInfoListening();
        }
        if(socketUtils.mReceiveThread != null){
            socketUtils.stopListening();
        }
//        socketUtils.startAlarmListening();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Boolean boo = true;
        while (boo){
            if(!socketUtils.alarmVal.equals("")){
                if(!socketUtils.alarmVal.equals("")){
                    boo = false;
                    Message msg = new Message();
                    msg.what = MSG_RECEIVE_DATA;
                    msg.obj = socketUtils.msgAlarmArray;
                    mHandler.sendMessage(msg);
                }
            }else {

                break;
            }
        }
        Message msg = new Message();
        msg.what = MSG_DEVICE_INIT;
        mHandler.sendMessage(msg);
        //getDeviceLisAll();
    }
}